;
cmedit.ConfigDownloadPath = (function($, window, document) {
	var thisContext;
	var tenantId = "";
    var userId = "";
    var token = "";
    var userName = "";
    var pageSize = 9;// 每页显示数
    var isSingleSelect = 0;// 是否可以选择栏目 0可以1不可以
    var isDeleteChecked = 1;// 是否可以删除栏目 0可以1不可以
    var myobj = [];// 所有栏目
    var columnlist = [];// 已存数据数据的栏目
    var isCanEdit = 1;// 是否可以编辑 0可以1不可以
    
	var ConfigDownloadPathClass = function(){
	
	};
	
	ConfigDownloadPathClass.prototype = {
		constructor:ConfigDownloadPathClass,
		//初始化
		init:function(){
			thisContext = this;
			//初始化开关
			SimpleSwitch.init();
			thisContext.initViewStyle();			
			
			thisContext.initData();
			thisContext.initEvent();
		},
		
		//初始化样式
		initViewStyle : function(){
			$("#download_switch button").css('margin-right','5%');
		},
		
		//初始化数据
		initData : function(){
			// 初始化用户信息
			thisContext.initUserSession();
			// 加载下载路径列表
			thisContext.listDownloadPathByCondition(1);
		},
		
		//初始化事件
		initEvent : function(){
			// 给下载路径列表搜索按钮绑定事件
			$("#searchDownloadPath").on('click', function() {
				// 加载列表
				thisContext.listDownloadPathByCondition(1);
			});
			// 禁用rightDiv下相关元素
			thisContext.disablerightDiv("rightDiv");
			
			// 给下载文件类型选择框绑定事件
			$("#downloadPathType").on('click', function() {
				thisContext.updateSimple();
			});
			// 新增下载路径按钮绑定事件
			$("#addDownloadPath").on('click', function() {
				thisContext.addDownloadPath();
			});
			// 编辑下载路径按钮绑定事件
			$("#updateDownloadPath").on('click', function() {
				if($("#downloadPathGuid").val()){
					thisContext.enablerightDiv("rightDiv");
				}else{
					alert("请选择一条修改数据");
				}
			});
			// 删除按钮绑定事件
			$("#deleteDownloadPath").on('click', function() {
				if($("#downloadPathGuid").val()){
					thisContext.deleteDownloadPath();
				}else{
					alert("请选择一条删除数据");
				}
			});
			// 取消按钮绑定事件
			$("#cancelDownloadPath").on('click', function() {
				// 加载下载路径列表
				thisContext.listDownloadPathByCondition(1);
			});
			// 保存按钮绑定事件
			$("#saveDownloadPath").on('click', function() {
				thisContext.saveDownloadPath();
			});
			$("#download_switch button").on('click', function(e) {
                var addGroup = 0;
                if ($(this).hasClass("on")) {
					addGroup = 1;
					$(".auto_download").show();
                } else { 
					addGroup = 0;
					$(".auto_download").hide();
                }
                
            });
		},
		
		/**
		 * 保存下载路径信息
		 */
		saveDownloadPath : function(){
			// 获取参数
			var downloadPathGuid = $("#downloadPathGuid").val();
			var downloadName = $("#downloadName").val();
			var downloadPathType = $("#downloadPathType").val();
			var downloadPath = $("#downloadPath").val();
			var downloadHint = $("#downloadHint").val();
			thisContext.getSelectedColumn();
			var downloadColumnRelations = JSON.stringify(columnlist);
			
			// 参数校验
			if (!cmedit.global.isNotEmpty(downloadName)) {
				alert("下载名称不能为空！");
				return false;
			}
			if (!cmedit.global.isNotEmpty(downloadPath)) {
				alert("下载路径不能为空！");
				return false;
			}
			
			/*if (downloadPathType == 1) {
				var pattStr = /^ftp:\/\/([a-zA-Z0-9_-])+:([a-zA-Z0-9_-])+@(([1-9]|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5])))\.)((d|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5])))\.){2}([1-9]|([1-9]\d)|(1\d\d)|(2([0-4]\d|5[0-5])))$/;
				var patt1=new RegExp(pattStr);
				if (!patt1.test(downloadPath)) {
					alert("下载路径不合法！");
				}
			} else {
				
			}*/
			
			if (columnlist.length < 1) {
				alert("下载路径所属栏目不能为空！");
				return false;
			}
			var postData = {
					"downloadPathGuid" : downloadPathGuid,
					"downloadName" : downloadName,
					"downloadPathType" : downloadPathType,
					"downloadPath" : downloadPath,
					"downloadHint" : downloadHint,
					"downloadColumnRelations" : downloadColumnRelations,
					"mainType" : 0,
					"autoDownload":0
				};
			if($("#download_switch button").hasClass("on")){
				var downloadFileType  = $("#downloadFileType").val();
				var enableAttachmentDownload  = 0;
				if($("#enableAttachmentDownload").is(':checked')){
					enableAttachmentDownload = 1;
				}
				postData.autoDownload = 1;
				postData.downloadFileType = downloadFileType;
				postData.enableAttachmentDownload = enableAttachmentDownload;
			}
			thisContext.ajaxRequest({
				async : false,
				url : cmedit.global.cmsPath + "DownloadManageController/saveDownloadPath",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						console.log("保存成功");
						alert("修改/新增成功");
						// 加载列表
						thisContext.listDownloadPathByCondition(1);
						// 禁用表单
						thisContext.disablerightDiv("rightDiv");
					} else {
						alert(data.msg);
					}
				}
			});
		},
		
		/**
		 * 新增下载路径按钮点击事件
		 */
		addDownloadPath : function(){
			// 清空表单内容
			thisContext.clearDownloadPathInput();
			// 触发选择项提示
			$("#downloadPathType").click();
			// 解除禁用状态
			thisContext.enablerightDiv("rightDiv");
		},
		
		/**
		 * 清空表单内容
		 */
		clearDownloadPathInput : function(){
			// 清空下载管理表单编辑区域
			$("#typeSimple").html("");
			$("#downloadPathGuid").val("");
			$("#downloadName").val("");
			$("#downloadPathType").val(1);
			$("#downloadPath").val("");
			$("#downloadHint").val("");
			$("#download_switch button").removeClass("on");
			$("#downloadFileType").val("1");
			$("#enableAttachmentDownload").prop("checked", false);
			$(".auto_download").hide();
			// 清空所选栏目区域
			columnlist = [];
			thisContext.showCheckColumnList(columnlist);
			// 重新加载所有栏目
			thisContext.initColumnInfoByInput();
			
		},

		/**
		 * 单选栏目
		 * @param id
		 * @param name
		 */
		enableSingleIcon : function(id,name){
			// 先判断单选框是否已经禁用
			if($("#" + id).hasClass('tube_check')){
				// 如果已选中,取消勾选权限
				if ($("#" + id).hasClass('icon-radio-checked')) { 
					$("#" + id).removeClass('icon-radio-checked');
					$("#" + id).addClass('icon-radio');
				} else {
					$("#" + id).addClass('icon-radio-checked');
					$("#" + id).removeClass('icon-radio');
				}
				
				var html = "";
				if ($("#" + id).hasClass('icon-radio-checked')) {
					html += '<tr id="checked'
							+ id
							+ '"><td width="90%">'
							+ name
							+ '</td><td><i id = "del'
							+ id
							+ '&&'
							+ name
							+ '"  onclick="javascript:cmedit.ConfigDownloadPath.deleteCheckedColumn(\''
							+ id
							+ '\',\''
							+ name
							+ '\')" class="icon iconfont icon-close tube_close"></i></td></tr>';
					$("#columns_checked").append(html);
				} else {
					$("#checked" + id).remove();
				}
				
				// 计算选中栏目数
				thisContext.checkedNum();
			}
		},
		
		/**
		 * 全选栏目
		 */
		enableAllIcon : function(){
			// 先判断全选框是否已经禁用
			if($(".all").hasClass('tube_check')){
				$(".all").unbind('click').on('click',
						function() {
							if ($('.all').hasClass('icon-radio-checked')) { // 如果已选中,取消勾选权限
								$('.all').removeClass('icon-radio-checked');
								$('.all').addClass('icon-radio');
								$('.one').each(function() {
									$(this).removeClass('icon-radio-checked');
									$(this).addClass('icon-radio');
								});
								if (myobj.length > 0) {
									for (var i = 0; i < myobj.length; i++) {
										$("#checked" + myobj[i].id).remove();
									}
									thisContext.checkedNum();
								}
							} else {
								$('.all').addClass('icon-radio-checked');
								$('.all').removeClass('icon-radio');
								$('.one').each(function() {
									$(this).addClass('icon-radio-checked');
									$(this).removeClass('icon-radio');
								});
								if (myobj.length > 0) {
									for (var i = 0; i < myobj.length; i++) {
										$("#checked" + myobj[i].id).remove();
									}
									var html = "";
									for (var i = 0; i < myobj.length; i++) {
										html += '<tr id="checked'
												+ myobj[i].id
												+ '"><td width="90%">'
												+ myobj[i].name
												+ '</td><td><i id = "del'
												+ myobj[i].id
												+ '&&'
												+ myobj[i].name
												+ '"  onclick="javascript:cmedit.ConfigDownloadPath.deleteCheckedColumn(\''
												+ myobj[i].id
												+ '\',\''
												+ myobj[i].name
												+ '\')" class="icon iconfont icon-close tube_close"></i></td></tr>';
									}
									$("#columns_checked").append(html);
									thisContext.checkedNum();
								}
							}
						});
			}
			
		},
		
		/**
		 * 去除所选栏目
		 * 
		 * @param id
		 * @param name
		 */
		deleteCheckedColumn : function(id, name){
			if (isCanEdit == 0) {
				$("#" + id).removeClass('icon-radio-checked');
				$("#" + id).addClass('icon-radio');
				$("#checked" + id).remove();
				thisContext.checkedNum();
			}
		},
		
		/**
		 * 计算选择的总数
		 */
		checkedNum : function(){
			var checkedColumnNum = $(".tube_close").length;
			var columnsObj = $(".tube_close");
			$("#columnNum").html(checkedColumnNum);
			var size = 0;
			if (myobj.length > 0) {
				for (var i = 0; i < myobj.length; i++) {
					if (columnsObj.length > 0) {
						for (var j = 0; j < columnsObj.length; j++) {
							var columns = columnsObj[j].id.substring(3,
									columnsObj[j].id.length);
							var column = columns.split("&&");
							if (myobj[i].id == column[0]) {
								size += 1;
							}
						}
					}
				}
			}
			if (size < myobj.length) {
				$('.all').removeClass('icon-radio-checked');
				$('.all').addClass('icon-radio');
			} else {
				$('.all').addClass('icon-radio-checked');
				$('.all').removeClass('icon-radio');
			}
		},
		/**
		 * 解除元素禁用
		 * @param divid
		 */
		enablerightDiv : function(divid){
			$("#" + divid).find("input").each(function() {
				$(this).removeAttr("disabled");
			});
			$("#" + divid).find("button").each(function() {
				$(this).removeAttr("disabled");
			});
			$("#" + divid).find("textarea").each(function() {
				$(this).removeAttr("disabled");
			});
			$("#" + divid).find("select").each(function() {
				$(this).removeAttr("disabled");
			});
			$(".one").removeClass("tube_check_disabled").addClass("tube_check");
			$(".all").removeClass("tube_check_disabled").addClass("tube_check");
			isCanEdit = 0;
			thisContext.enableAllIcon();
		},

		/**
		 * 禁用元素
		 * @param divid
		 */
		disablerightDiv : function(divid){
			$("#" + divid).find("input").each(function() {
				$(this).attr("disabled", "disabled");
			});
			$("#" + divid).find("button").each(function() {
				$(this).removeAttr("disabled").attr("disabled",true);
			});
			$("#" + divid).find("textarea").each(function() {
				$(this).attr("disabled", "disabled");
			});
			$("#" + divid).find("select").each(function() {
				$(this).attr("disabled", "disabled");
			});
			$(".all").unbind('click');
			$(".one").removeClass("tube_check").addClass("tube_check_disabled");
			$(".all").removeClass("tube_check").addClass("tube_check_disabled");
			isCanEdit = 1;
		},
		
		/**
		 * 根据各种条件，分页查询下载路径信息
		 */
		listDownloadPathByCondition : function(currentPage){
			
			var postData = {
				"currentPage" : currentPage,
				"pageSize" : pageSize,
				"downloadName" : $('#searchDownloadName').val(),
				"mainType" : 0
			};
			
			thisContext.ajaxRequest({
				async : false,
				url : cmedit.global.cmsPath + "DownloadManageController/getDownloadPathByPage",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						var html = template('downloadPathList_script',data);
						if(html){
							$('#downloadPathList').html(html);
						}else{
							$('#downloadPathList').html("<span class='noResults'>暂无数据<span>");
						}
						thisContext.showPages(data);
						if (data.data.list.length == 0) {
							// 清空表单内容
							thisContext.clearDownloadPathInput();
						} else {
							// 默认选中第一条数据
							$("#downloadPathList tr:eq(1)").click();
						}
					} else {
						alert(data.msg);
					}
				}
			});
		},
		
		 /**
         * 展示页码
         * @param data
         */
        showPages : function(data){
        	var pages = data.data;
			var data = {
				pages : pages
			}
			var pagehtml = template('parameter_page', data);
			$('#paging').html(pagehtml);
        },
        
        /**
         * 展现下载列表
         * @param curpage
         */
        listDownloadTarget : function(curpage){
        	thisContext.listDownloadPathByCondition(curpage);
        	thisContext.disablerightDiv("rightDiv");
        },
		
		
		/**
		 * 获取下载路径详情
		 * @param downloadPathGuid
		 * @param selectedobj
		 */
		showDownloadPathDetail : function(downloadPathGuid,selectedobj){
			//设置样式
			$(selectedobj).parent().find("tr.trActive").toggleClass("trActive");//取消原先选中行
		    $(selectedobj).toggleClass("trActive");//设定当前行为选中行
			// 查询详情
			var postData = {
					"downloadPathGuid" : downloadPathGuid
				};
			thisContext.ajaxRequest({
				async : false,
				url : cmedit.global.cmsPath + "DownloadManageController/getDownloadPathByGuid",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						// 填充编辑区域
						var dataObj = data.data;
						$("#downloadPathGuid").val(dataObj.downloadPathGuid);
						$("#downloadName").val(dataObj.downloadName);
						$("#downloadPath").val(dataObj.downloadPath);
						$("#downloadPathType").val(dataObj.downloadPathType);
						$("#downloadHint").val(dataObj.downloadHint);
						$("#columnName").val("");
						if(dataObj.autoDownload == 1){
							$("#download_switch button").addClass("on");
							$("#downloadFileType").val(dataObj.downloadFileType);
							if(dataObj.enableAttachmentDownload == 1){
								$("#enableAttachmentDownload").prop("checked", true);
							}
							$(".auto_download").show();
						}else{
							$("#download_switch button").removeClass("on");
							$(".auto_download").hide();
						}
						// 加载下载路径所属关联栏目列表
						thisContext.showCheckColumnList(dataObj.downloadColumnRelationList);
						// 更新全部栏目列表
						thisContext.initColumnInfoByInput();
						// 禁用表单
						thisContext.disablerightDiv("rightDiv");
					} else {
						alert(data.msg);
					}
				}
			});
		},
		
		/**
		 * 展现已选栏目列表
		 */
		showCheckColumnList : function(list){
			var data = {};
			data.data = list;
			if(list.length === 0){
				data.num = 0;
			}else{
				data.num = columnlist.length;
			}
			var html = template('columns_checked_script',data);
			if(html){
				$('#columns_checked').html(html);
			}else{
				$('#columns_checked').html("<span class='noResults'>暂无数据<span>");
			}
		},
		
		/**
         * 根据输入内容模糊检索栏目信息
         */
		initColumnInfoByInput : function(){
			// 查询详情
			var columnName = $('#columnName').val();
			var postData = {
					"columnName" : columnName,
					 key : window.localStorage.getItem("portalKey")
				};
			thisContext.ajaxRequest({
				async : false,
				url : cmedit.global.cmsPath + "UserInfoController/fuzzySearchColumn",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						myobj = data.data;
						var html = template('allColumnList_script',data);
						if(html){
							$('#allColumnList').html(html);
						}else{
							$('#allColumnList').html("<span class='noResults'>暂无数据<span>");
						}
						$('#columnName').val(columnName);
						if(cmedit.global.isNotEmpty(columnName)){
							$("#columnName").focus();
						}
						// 将以选中的栏目回显到待选列表
						thisContext.getSelectedColumn();
						if (myobj.length > 0) {
							for (var i = 0; i < myobj.length; i++) {
								if (columnlist.length > 0) {
									for (var j = 0; j < columnlist.length; j++) {
										if (myobj[i].id == columnlist[j].columnId) {
											$("#" + myobj[i].id).removeClass(
													"icon-radio");
											$("#" + myobj[i].id).addClass(
													"icon-radio-checked");
										}
									}
								}
							}
						}
						thisContext.checkedNum();
						$(".one").removeClass("tube_check_disabled").addClass("tube_check");
						$(".all").removeClass("tube_check_disabled").addClass("tube_check");
						thisContext.enableAllIcon();
					} else {
						alert(data.msg);
					}
				}
			});
        },
        
        /**
         * 获取选中的栏目信息
         */
        getSelectedColumn : function(){
        	columnlist = [];
        	var columnsObj = $(".tube_close");
        	if (columnsObj.length > 0) {
        		for (var i = 0; i < columnsObj.length; i++) {
        			var columnObj = {};
        			var columns = columnsObj[i].id
        					.substring(3, columnsObj[i].id.length);
        			var column = columns.split("&&");
        			columnObj.columnId = column[0];
        			columnObj.columnName = column[1];
        			columnlist.push(columnObj);
        		}
        	} else{
        		columnlist = [];
        	}
        },
        
        /**
         * 删除下载路径
         */
        deleteDownloadPath : function(){
        	var downloadPathGuid = $("#downloadPathGuid").val();
        	if(confirm("确定删除该下载路径?")){
        		var postData = {
					"downloadPathGuid" : downloadPathGuid
				};
				thisContext.ajaxRequest({
					async : false,
					url : cmedit.global.cmsPath + "DownloadManageController/deleteDownloadPath",
					type : 'POST',
					data : postData,
					success : function(data){
						if (data.status == true || data.status == 'true') {
							console.log("删除成功");
							alert("删除成功");
							// 加载列表
							thisContext.listDownloadPathByCondition(1);
							// 禁用表单
							thisContext.disablerightDiv("rightDiv");
						} else {
							alert(data.msg);
						}
					}
				});
        	}

        },
		
		/**
         * 初始化分页
         */
        initPage : function(totalPage){
        	$("#pagination").whjPaging({
                totalPage: totalPage,
                showPageNum: 4,
                firstPage: '<i class="iconfont icon-diyiye"></i>',
                previousPage: '<i class="iconfont icon-shangyiye"></i>',
                nextPage: '<i class="iconfont icon-xiayiye"></i>',
                lastPage: '<i class="iconfont icon-weiye"></i>',
                skip: 'skip',
                confirm: 'go',
                refresh: 'refresh',
                totalPageText: 'the total {} pages',
                isShowFL: true,
                isShowPageSizeOpt: false,
                isShowSkip: false,
                isShowRefresh: false,
                isShowTotalPage: false,
                isResetPage: true,
                callBack: function (currPage, pageSize) {
                    thisContext.listDownloadPathByCondition(currPage);
                }
            });
        },
        
        /**
         * 切换提示信息
         */
        updateSimple: function () {
        	var downloadPathType = $("#downloadPathType").val();
        	if (downloadPathType == "1") {
        		$("#typeSimple").html("FTP格式：ftp://user:password@ip:port/filePath");
        	} else {
        		$("#typeSimple").html("UNC格式：\\\\\\\\ip\\\\orign\\\\orign\\\\filePath\\\\");
        	}
        },
		
		/**
		 * 初始化用户信息
		 * @returns {Boolean}
		 */
		initUserSession: function () {
        	token = cmedit.global.getParameterFromUrl("token");
        	userId = cmedit.global.getParameterFromUrl("userId");
        	userName = cmedit.global.getParameterFromUrl("userName");
        	tenantId = cmedit.global.getParameterFromUrl("tenantId");
        	
        	if(!cmedit.global.isNotEmpty(token)){
        		alert("token为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(userId)){
        		alert("userId为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(userName)){
        		alert("userName为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(tenantId)){
        		alert("tenantId为空");
        		return false;
        	}
        },
        
        /**
         * 封装的Ajax
         * @param opts
         */
        ajaxRequest: function (opts) {
            // 一.设置默认参数
            var defaults = {
                url: '',
                type: '',
                data: '',
                cache: true,
                async: false,
                dataType: 'json',
//                contentType: "application/json;charset=UTF-8",
                success: function () {
                },
                error: function () {
                }
            };

            // 二.用户参数覆盖默认参数
            for (var key in opts) {
                defaults[key] = opts[key];
            }
            
            // 三.开始组装ajax
            $.ajax({
                url: defaults.url,
                type: defaults.type,
                data: defaults.data,
                async: defaults.async,
                cache: defaults.cache,
                dataType: defaults.dataType,
                contentType: defaults.contentType,
                beforeSend: function (XHR) {
                    XHR.setRequestHeader("userId", userId);
                    XHR.setRequestHeader("userName", encodeURIComponent(userName));
                    XHR.setRequestHeader("tenantId", tenantId);
                    XHR.setRequestHeader("token", token);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("错误信息" + errorThrown.toString());
                },
                success: defaults.success
            });
        },
		
		
		
		
	};
	return new ConfigDownloadPathClass();
})(jQuery, window, document);

$(cmedit.ConfigDownloadPath.init());